package org.kirhgoff.mathbot;

import org.aicontest.PlanetWars;

public class MatematicBot {
	private static Gene gene = Properties.SIMPLE_GENE;
	
	public static void DoTurn(final PlanetWars pw) {
		LOGGER.info("=============== TURN =================");
		final long startedAt = System.currentTimeMillis();
		try {
			final MathModule module = new MathModule (gene);
			final World world = new World (pw, module);
			LOGGER.info(world.toString());
			Strategy strategy = new Strategy (world, module);

			strategy.doTurn (new IssueOrderCallback () {
				@Override
				public boolean issueOrder(PlanetInfo source, PlanetInfo target, int shipsToSend) {
					//issue real order
					pw.IssueOrder(source.id (), target.id(), shipsToSend);
					//update world information
					world.updateWorldAfterThisOrder (source, target, shipsToSend);
					LOGGER.info("ISSUE ORDER sent " + shipsToSend + " ships\nfrom=" + source + "\nto=" + target);
					return true;
				}
			});

			LOGGER.info("Full turn time [" + (System.currentTimeMillis() - startedAt) + " ms]");
		}
		catch (Exception e) {
			LOGGER.error(e);
			e.printStackTrace (System.err);
			throw new RuntimeException (e);
		}
		finally {
			LOGGER.flush ();
		}
	}
	
	public static void main(String[] args) {
		String line = "";
		String message = "";
		int c;
		try {
			while ((c = System.in.read()) >= 0) {
				switch (c) {
				case '\n':
					if (line.equals("go")) {
						PlanetWars pw = new PlanetWars(message);
						DoTurn(pw);
						pw.FinishTurn();
						message = "";
					} else {
						message += line + "\n";
					}
					line = "";
					break;
				default:
					line += (char) c;
					break;
				}
			}
		} catch (Exception e) {
			System.out.println("Error while reading input: " + e.getMessage());
			e.printStackTrace();
		}
	}
}
